<template>
  <XnDialog
    custom-class="add-account-dialog"
    :title="isEdit ? '编辑用户' : ''"
    :visible.sync="selfVisible"
    @close="closeDialog">
    <template slot="title">
      <ul class="tabUl">
        <li class="tabLi" :class="{ active: activeTab == 1 }" @click="onChangeDialogTab(1)">添加用户</li>
        <li class="tabLi" :class="{ active: activeTab == 2 }" @click="onChangeDialogTab(2)">批量导入用户</li>
      </ul>
    </template>
    <el-form
      ref="accountForm"
      :model="accountForm"
      :rules="rules"
      size="small"
      label-width="100px"
      label-suffix="："
      class="dialog-con"
      v-if="activeTab === 1">
      <el-divider content-position="left">登录信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="accountForm.userName" placeholder="请输入" :maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="登录账号" prop="loginName">
            <el-input
              v-model="accountForm.loginName"
              placeholder="请输入"
              autocomplete="off"
              :maxlength="100"
              show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="登录密码" prop="loginPassword">
            <el-input
              v-model="accountForm.loginPassword"
              v-if="showPwdInput"
              placeholder="请输入"
              show-password
              autocomplete="new-password"
              :maxlength="15"
              show-word-limit>
              <el-button slot="append" v-if="temporaryPwd" @click="onCancelChangePwd">取消修改</el-button>
            </el-input>
            <el-button v-else type="primary" @click="onChangePwd">修改密码</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="头像" prop="headUrl">
        <UploadFile
          :maxLimit="1"
          :showLabel="false"
          :file-list="albumList"
          styleControl="picture"
          @imginfo="getUploadInfo"
          @delFileData="delFileData"
          accept=".jpeg,.png,.jpg"
          layout="block"></UploadFile>
      </el-form-item>
      <el-form-item label="分管部门" prop="leadChargeDepart">
        <OrganTreeSelect
          multiple
          :flat="true"
          v-model="accountForm.leadChargeDepart"
          :tenantId.sync="accountForm.tenantId"></OrganTreeSelect>
      </el-form-item>
      <el-divider content-position="left">基本信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="手机号码" prop="telephone">
            <el-input v-model="accountForm.telephone" placeholder="请输入" :maxlength="11" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="固定电话" prop="fixedphone">
            <el-input v-model="accountForm.fixedphone" placeholder="请输入" :maxlength="15" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="accountForm.email" placeholder="请输入" :maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="accountForm.birthday"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              :default-value="defaultValue"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="accountForm.gender" placeholder="请选择" clearable filterable>
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="政治面貌" prop="politicalOutlook">
            <el-select v-model="accountForm.politicalOutlook" placeholder="请选择" clearable filterable>
              <el-option
                v-for="item in politicalOutlookList"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="学历" prop="education">
            <el-select v-model="accountForm.education" placeholder="请选择" clearable filterable>
              <el-option
                v-for="item in educationList"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="人员类别" prop="userCategory">
            <el-select v-model="accountForm.userCategory" placeholder="请选择" clearable filterable>
              <el-option
                v-for="item in userCategoryList"
                :key="item.code"
                :label="item.name"
                :value="Number(item.code)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上级领导" prop="mainLeader">
            <el-select v-model="accountForm.mainLeader" placeholder="请选择" filterable>
              <el-option
                v-for="item in mainLeaderList"
                :key="item.id"
                :label="item.userName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="8">
          <el-form-item label="主要领导" prop="mainLeadership">
            <el-select v-model="accountForm.mainLeadership" placeholder="请选择" filterable multiple>
              <el-option
                v-for="item in mainLeaderList"
                :key="item.id"
                :label="item.userName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="accountForm.remark" placeholder="请输入" maxlength="200" show-word-limit></el-input>
            </el-form-item> -->
      <el-form-item label="用户身份" prop="userIdentity">
        <el-radio-group v-model="accountForm.userIdentity">
          <el-radio :label="item.code" v-for="item in userIdentityList" :key="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="用户状态" prop="userStatus">
        <el-radio-group v-model="accountForm.userStatus">
          <el-radio :label="item.code" v-for="item in userStatusList" :key="item.code">
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left">权限信息</el-divider>
      <el-row v-for="(item, index) in accountForm.orgPostList" :key="index">
        <el-col :span="7">
          <el-form-item label="所属机构" :rules="rules.orgId" :prop="`orgPostList.${index}.orgId`">
            <OrganTreeSelect
              v-model="item.orgId"
              @onSelect="onOrgChange($event, index)"
              :tenantId.sync="accountForm.tenantId"></OrganTreeSelect>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="职位"
            :rules="rules.orgPostId"
            :prop="`orgPostList.${index}.orgPostId`"
            label-width="80px">
            <el-select v-model="item.orgPostId" placeholder="请选择">
              <el-option
                v-for="item1 in item.orgPostIdList"
                :key="item1.id"
                :label="item1.postName"
                :value="item1.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主要领导" prop="isMainLead">
            <el-radio-group v-model="item.isMainLead">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="operBox">
            <i class="iconPr el-icon-circle-plus" @click="onAddRemove(1)"></i>
            <i
              class="iconPr el-icon-remove"
              @click="onAddRemove(0, index)"
              v-if="index !== 0 && accountForm.orgPostList.length !== 1"></i>
            <el-radio @change="onRadioChange($event, index)" v-model="item.isDefault" :label="1">设置默认</el-radio>
          </div>
        </el-col>
      </el-row>
      <el-form-item label="角色" prop="roleIds">
        <el-select v-model="accountForm.roleIds" placeholder="请选择" filterable multiple>
          <el-option :label="item.roleName" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-divider content-position="left">岗位职责</el-divider>
      <el-form-item label="岗位职责" prop="postDuty">
        <el-input
          v-model="accountForm.postDuty"
          type="textarea"
          placeholder="请输入"
          :rows="6"
          show-word-limit
          :maxlength="500"></el-input>
      </el-form-item>
    </el-form>
    <div v-show="activeTab == 2">
      <PeopleImport verifyActivation="0" @success="importSuccess"></PeopleImport>
    </div>
    <div class="btn-box" v-if="activeTab == 1">
      <el-button size="small" @click.stop="closeDialog">取消</el-button>
      <el-button size="small" type="primary" @click.stop="onFormSave">确定</el-button>
    </div>
  </XnDialog>
</template>
<script>
import XnDialog from '@com/xnDialog.vue'
import { pwdReg2, phoneReg } from '@utility/regExps.js'
import { randomPassword } from '@utility/utility.js'
import { listRoleData, listUiasOrgPost, listCodeData, listUserData } from '@api/modules/system.js'
import { cloneDeep } from 'lodash'
import OrganTreeSelect from '@com/OrganTreeSelect.vue'
import UploadFile from '@com/UploadFile.vue'
import PeopleImport from './PeopleImport'

export default {
  name: 'AccountDialog',
  components: { XnDialog, UploadFile, OrganTreeSelect, PeopleImport },
  emits: ['close', 'submit'],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    info: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    // const checkAccount = (rule, value, cb) => {
    //   if (!value) {
    //     cb(new Error('账号不能为空'))
    //   } else if (/^[a-zA-Z][a-zA-Z0-9_]{7,15}$/.test(value)) {
    //     cb()
    //   } else {
    //     cb(new Error('8~16位以字母开头的字母和数字的组合'))
    //   }
    // }
    const checkPwd = (rule, value, cb) => {
      if (!value) {
        cb(new Error('密码不能为空'))
      } else if (pwdReg2.test(value)) {
        cb()
      } else {
        cb(new Error('8~16位数字、字母和特殊符号的组合'))
      }
    }
    const checkPhone = (rule, value, cb) => {
      if (phoneReg.test(value)) {
        return cb()
      }
      cb(new Error('您输入的手机号码不是有效格式'))
    }
    return {
      selfVisible: false,
      accountForm: {
        id: '',
        userName: '',
        loginName: '',
        loginPassword: '',
        headUrl: '',
        telephone: '',
        fixedphone: '',
        email: '',
        birthday: '',
        gender: '',
        politicalOutlook: '',
        education: '',
        userCategory: '',
        mainLeader: '',
        mainLeadership: '',
        userIdentity: '',
        userStatus: '2',
        roleIds: [],
        orgPostList: [
          {
            isDefault: 1,
            orgId: '',
            orgPostId: '',
            orgPostIdList: [],
          },
        ],
        postName: '',
        tenantId: '',
        postDuty: '',
      },
      rules: {
        userName: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
        // loginName: [
        //   { required: true, validator: checkAccount, trigger: 'blur' },
        //   { required: true, validator: checkAccount, trigger: 'input' },
        // ],
        loginName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
        orgId: [
          { required: true, message: '请选择所属机构', trigger: 'change' },
          { required: true, message: '请选择所属机构', trigger: 'blur' },
        ],
        orgPostId: [{ required: true, message: '请选择职位', trigger: 'change' }],
        telephone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkPhone,
            trigger: 'blur',
          },
        ],
        mainLeader: [{ required: true, message: '请选择上级领导', trigger: 'blur' }],
        userIdentity: [{ required: true, message: '请选择用户身份', trigger: 'blur' }],
        userStatus: [{ required: true, message: '请选择用户状态', trigger: 'blur' }],
        password: [],
      },
      roleList: [],
      checkPwd: checkPwd,
      inpType: 'password',
      editPass: false,
      showPwdInput: false,
      temporaryPwd: '',
      pickerOptions: {
        disabledDate(time) {
          const before = Date.now() - 24 * 60 * 60 * 1000
          return time.getTime() > before
        },
      },
      defaultValue: '',
      educationList: [],
      userCategoryList: [],
      politicalOutlookList: [],
      mainLeaderList: [],
      userStatusList: [],
      albumList: [],
      userIdentityList: [],
      activeTab: 1,
    }
  },
  watch: {
    visible(bool) {
      this.selfVisible = bool
      if (bool) {
        this.activeTab = 1
        this.onAddEdit(this.info)
      }
    },
    info: {
      handler(obj) {
        if (obj && obj.id) {
          // console.log('obj :>> ', obj)
        }
      },
      deep: false,
      immediate: true,
    },
  },
  computed: {
    isEdit() {
      return this.accountForm.id
    },
  },
  methods: {
    async getRoleList() {
      const { status, data } = await listRoleData()
      if (status === 200 && data && data.length) {
        this.roleList = data
      } else {
        this.roleList = []
      }
    },
    closeDialog() {
      this.$refs.accountForm && this.$refs.accountForm.resetFields()
      this.selfVisible = false
      this.editPass = false
      this.activeTab = 1
      this.accountForm = {
        id: '',
        userName: '',
        userStatus: '',
        telephone: '',
        loginName: '',
        password: '',
        postName: '',
        orgPostList: [
          {
            isDefault: 1,
            orgId: '',
            orgPostId: '',
            orgPostIdList: [],
          },
        ],
        roleIds: [],
        headUrl: '',
      }
      this.$emit('close', false)
      this.$emit('update:visible', false)
    },
    togglePwdDisplay() {
      this.inpType = this.inpType === 'password' ? 'text' : 'password'
    },
    onOrgChange(id, inx) {
      this.$set(this.accountForm.orgPostList[inx], 'orgPostId', '')
      this.$refs.accountForm.clearValidate(`orgPostList.${inx}.orgPostId`)
      this.listUiasOrgPostdata(id, inx)
    },
    listUiasOrgPostdata(orgId, inx) {
      listUiasOrgPost({
        pageNum: 1,
        pageSize: 1000,
        orgId: orgId,
      }).then(res => {
        if (res.status === 200) {
          const content = (res.data && res.data.content) || []
          this.$set(this.accountForm.orgPostList[inx], 'orgPostIdList', content)
          if (!this.info.id) {
            this.$set(this.accountForm.orgPostList[inx], 'orgPostId', content.length ? content[0].id : '')
          }
        } else {
          this.$set(this.accountForm.orgPostList[inx], 'orgPostIdList', [])
        }
      })
    },
    onFormSave() {
      if (this.editPass) {
        this.$refs.accountForm.validateField('loginPassword')
      }
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          const accountForm = {
            ...this.accountForm,
          }
          // if (Array.isArray(accountForm.mainLeader)) {
          //   accountForm.mainLeader = accountForm.mainLeader.join(',')
          // } else {
          //   accountForm.mainLeader = accountForm.mainLeader || ''
          // }
          accountForm.mainLeader = accountForm.mainLeader || ''
          // if (this.info.id) {
          //   accountForm.roleIds = this.info.roleIds
          //   accountForm.orgPostList = this.info.orgPostList
          // }
          if (this.albumList.length) {
            accountForm.headUrl = this.albumList[0].thumbnailPath
          }
          accountForm.userCategory = accountForm.userCategory || ''
          // console.log('object :>> ', cloneDeep(accountForm))
          this.$emit('submit', cloneDeep(accountForm))
          this.closeDialog()
        }
      })
    },
    editPassword() {
      this.rules.loginPassword = [{ required: true, validator: this.checkPwd, trigger: 'blur' }]
      this.editPass = true
      this.accountForm.password = ''
    },
    cancelEditPass() {
      this.$refs.accountForm.clearValidate('password')
      if (this.isEdit) {
        delete this.rules.password
        this.editPass = false
      } else {
        const passwordLength = 10
        this.accountForm.password = randomPassword(passwordLength)
        this.inpType = 'text'
        this.$refs.accountForm.validateField('loginPassword')
      }
    },
    onCancelChangePwd() {
      this.$set(this.accountForm, 'loginPassword', this.temporaryPwd)
      this.showPwdInput = false
    },
    onChangePwd() {
      this.temporaryPwd = this.accountForm.loginPassword
      this.$set(this.accountForm, 'loginPassword', '')
      this.showPwdInput = true
    },
    onChangeTenantId() {},
    // 获取上传文件信息
    getUploadInfo(list) {
      if (list.length > 0) {
        this.accountForm.headUrl = list[0].idAddr + list[0].fileVisitUrl
      }
    },
    delFileData(n) {
      this.accountForm.headUrl = ''
      this.albumList.splice(n, 1)
    },
    onAddRemove(type, index) {
      if (type === 1) {
        this.accountForm.orgPostList.push({
          isMainLead: 0,
          isDefault: 0,
          orgPostIdList: [],
        })
      } else {
        this.accountForm.orgPostList.splice(index, 1)
      }
    },
    onRadioChange(data, index) {
      for (let i = 0; i < this.accountForm.orgPostList.length; i++) {
        const item = this.accountForm.orgPostList[i]
        if (index === i) {
          item.isDefault = data
        } else {
          item.isDefault = 0
        }
      }
    },
    onAddEdit(data) {
      this.initListCodeDatadata('1000')
      this.initListCodeDatadata('1001')
      this.initListCodeDatadata('user_category')
      this.initListCodeDatadata('user_identity')
      this.initListCodeDatadata('user_status')
      if (this.$refs.accountForm) {
        this.$refs.accountForm.resetFields()
      }
      this.temporaryPwd = ''
      this.$set(this.accountForm, 'id', '')
      this.$set(this.accountForm, 'leadChargeDepart', [])
      this.albumList = []
      if (data && data.id) {
        if (data.orgPostList.length !== 0) {
          for (let i = 0; i < data.orgPostList.length; i++) {
            const item = data.orgPostList[i]
            this.listUiasOrgPostdata(item.orgId, i)
          }
        } else {
          data.orgPostList.push({
            isMainLead: 0,
            isDefault: 0,
            orgPostIdList: [],
          })
        }
        this.showPwdInput = false
        // 处理头像信息
        const { headUrl = '' } = data
        if (headUrl) {
          const fileType = headUrl.split('.').pop()
          this.albumList = [
            {
              fileType,
              url: headUrl,
              thumbnailPath: headUrl,
              sourcePath: headUrl,
            },
          ]
        }
        const postDuty = data.postDuty
          ? data.postDuty
              .replace(/<p>/g, '') // eslint-disable-line
              .replace(/<div>/g, '') // eslint-disable-line
              .replace(/<\/p>/g, '\r') // eslint-disable-line
              .replace(/<\/div>/g, '\r') // eslint-disable-line
              .replace(/<br>/g, '\r') // eslint-disable-line
          : ''

        const userStatus = String(data.userStatus)
        this.accountForm = { ...this.accountForm, ...data, postDuty, userStatus }
        this.getRoleList()
        // if (this.accountForm.mainLeader) {
        //   this.accountForm.mainLeader = this.accountForm.mainLeader.split(',')
        // }
        this.initdata()
      } else {
        this.rules.loginPassword = [{ required: true, validator: this.checkPwd, trigger: 'change' }]
        this.initdata()
        this.getRoleList()
        this.showPwdInput = true
        this.accountForm = {
          ...this.accountForm,
          orgPostList: [
            {
              isMainLead: 0,
              isDefault: 1,
              orgPostIdList: [],
            },
          ],
        }
      }

      // console.log('this.accountForm :>> ', this.accountForm)
    },
    /* 初始化参数配置 */
    initListCodeDatadata(codeType) {
      listCodeData(codeType).then(res => {
        const { status, data } = res
        if (status === 200) {
          if (codeType === '1000') {
            this.politicalOutlookList = data
          } else if (codeType === '1001') {
            this.educationList = data
          } else if (codeType === 'user_category') {
            this.userCategoryList = data
          } else if (codeType === 'user_identity') {
            this.userIdentityList = data
          } else if (codeType === 'user_status') {
            this.userStatusList = data
          }
        }
      })
    },
    /* 初始化人员数据 */
    initdata() {
      listUserData({
        pageNum: 1,
        pageSize: 10000,
        tenantId: localStorage.pskh_tenantId,
        key: '',
        orgId: '',
      }).then(res => {
        if (res.status === 200) {
          const { content } = res.data
          this.mainLeaderList = content
        }
      })
    },
    /* 弹出框tab切换 */
    onChangeDialogTab(type) {
      this.activeTab = type
    },
    importSuccess() {
      this.$emit('renewData')
    },
  },
}
</script>
<style lang="scss" scoped>
.add-account-dialog {
  ::v-deep &.el-dialog {
    width: 1200px;
    .dialog-con {
      max-height: 50vh;
      overflow: hidden scroll;
      height: 100%;
    }

    .el-form {
      .el-select,
      .el-date-editor {
        width: 100%;
      }
      .el-row {
        // padding-right: 25px;
        position: relative;
      }
      .operBox {
        display: flex;
        align-items: center;
        padding-left: 0.3rem;
        .el-radio {
          padding-top: 0.06rem;
        }
      }
      .iconPr {
        font-size: 26px;
        cursor: pointer;
        padding-top: 0.05rem;
        margin-right: 10px;
        /* position: absolute;
    right: -10px;
    top: 0.05rem; */
      }
      .textarea_p_box {
        position: relative;
      }
      .txt_limit_tip {
        position: absolute;
        right: 5px;
        bottom: 0px;
        font-size: 12px;
        color: #aaa;
      }
      .textarea {
        width: 100%;
        padding: 5px 15px;
        font-size: inherit;
        line-height: 1.5;
        box-sizing: border-box;
        min-height: 120px;
        max-height: 300px;
        margin-left: auto;
        margin-right: auto;
        outline: 0;
        border: 1px solid #c0c4cc;
        border-radius: 4px;
        word-wrap: break-word;
        overflow-x: hidden;
        overflow-y: auto;
        white-space: pre-line;
        &:focus {
          outline: 0;
          border-color: #409eff;
        }
      }
    }
    .btn-box {
      text-align: right;
      margin-top: 20px;
      border-top: 1px solid #dedede;
      padding-top: 20px;
    }
    .tabUl {
      display: flex;
      align-items: center;
      margin: 5px 0;
      .tabLi {
        margin-right: 20px;
        cursor: pointer;
        position: relative;
        transition: all linear 0.3s;
        &:after {
          content: '';
          position: absolute;
          bottom: -13px;
          left: 0;
          height: 2px;
          background: transparent;
          width: 100%;
        }
        &.active {
          transform: scale(1.1);
          font-weight: 600;
          &:after {
            background: #004db6;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-popover {
  &.password-tips-popover {
    .password-tip-con {
      .tips-title {
        font-size: 15px;
        list-style: 24px;
        margin-bottom: 10px;
        color: #333;
      }

      .tips-con {
        font-size: 13px;
        list-style: 20px;
        margin-bottom: 5px;
        color: #666;
      }
    }
  }
}
</style>
